import { WereWolfPlayerTeleport } from "@/werewolf/components/playerteleporter";
import { world } from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { Game, GameComponent, TeamScoreBoard } from "@sapi-game/main";
import { Vector3Utils } from "@sapi-game/utils";
import { EffectIds } from "@sapi-game/utils/vanila-data";
import { WereWolfMainState } from "./state";

export class WereWolfDaemon extends GameComponent<WereWolfMainState> {
    override onAttach(): void {
        this.subscribe(Game.events.interval, () => this.tick());

        //重生时传回家
        this.subscribe(world.afterEvents.playerSpawn, (t) => {
            const gamePlayer = this.context.players.getById(t.player.id);
            if (gamePlayer && gamePlayer.isValid) {
                this.state
                    .getComponent(WereWolfPlayerTeleport)
                    .tpToHouse(gamePlayer);
            }
        });
    }

    tick() {
        this.context.players.forEach((p) => {
            p.player.addEffect(EffectIds.FireResistance, 10, {
                showParticles: false,
            });
            //设置重生点为家里
            p.player.setSpawnPoint({
                dimension: Dimensions.Overworld,
                ...Vector3Utils.fromArray(
                    this.context.map.locations.housePos[p.no - 1]
                ),
            });
        });
        this.state.getComponent(TeamScoreBoard).refreshScoreBoard();
    }
}
